package mysql

import (
	"database/sql"
	"github.com/gin-gonic/gin"
	"xinduobang/stock/core"
	"xinduobang/stock/utils"
)

type Tx struct {
	tx  *sql.Tx
	ctx *gin.Context
}

// 初始化sql事务
func InitTx(c *gin.Context, dbName string) (*Tx, error) {
	db, err := core.GetMysql(dbName)
	if err != nil {
		utils.Errorf(c, "InitTx_Begin_GetMysql_Fail||err=%v", err.Error())
		return nil, err
	}

	tx, err1 := db.Begin()
	if err1 != nil {
		utils.Errorf(c, "InitTx_Begin_Fail||err=%v", err.Error())
		return nil, err1
	}

	return &Tx{
		ctx: c,
		tx:  tx,
	}, err
}

// ...
func (mtx *Tx) Commit() error {
	err := mtx.tx.Commit()
	if err != nil {
		utils.Errorf(mtx.ctx, "InitTx_Begin_Fail||err=%v", err.Error())
	}
	return err
}

// ...
func (mtx *Tx) Rollback() error {
	err := mtx.tx.Rollback()
	if err != nil {
		utils.Errorf(mtx.ctx, "Rollback_Rollback_Fail||err=%v", err.Error())
	}
	return err
}

func (mtx *Tx) Prepare(query string) (*sql.Stmt, error) {
	stmt, err := mtx.tx.Prepare(query)
	if err != nil {
		utils.Errorf(mtx.ctx, "Prepare_Fail||err=%v", err.Error())
	}
	return stmt, err
}

func (mtx *Tx) Exec(query string, args ...interface{}) (sql.Result, error) {
	result, err := mtx.tx.Exec(query, args...)
	if err != nil {
		utils.Errorf(mtx.ctx, "Exec_Fail||err=%v", err.Error())
	}
	return result, err
}

func (mtx *Tx) Query(query string, args ...interface{}) (*sql.Rows, error) {
	rows, err := mtx.tx.Query(query, args...)
	if err != nil {
		utils.Errorf(mtx.ctx, "Query_Fail||err=%v", err.Error())
	}
	return rows, err
}

func (mtx *Tx) QueryRow(query string, args ...interface{}) *sql.Row {
	row := mtx.tx.QueryRow(query, args...)

	return row
}

func (mtx *Tx) Stmt(stmt *sql.Stmt) *sql.Stmt {
	stmt = mtx.tx.Stmt(stmt)
	return stmt
}
